package com.example.forum.services.impl;

import com.example.forum.dao.ArticleHotMapper;
import com.example.forum.dto.ArticleScoreDTO;
import com.example.forum.model.ArticleHot;
import com.example.forum.services.IArticleHotServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ArticleHotServiceImpl implements IArticleHotServiceImpl {

    @Autowired
    private ArticleHotMapper articleHotMapper;

    @Bean
    public ArticleScoreDTO articleScoreDTO() {
        return new ArticleScoreDTO("null", 0.0,0L);
    }

    @Override
    public List<ArticleScoreDTO> selectTop() {
        List<ArticleHot> articleHots = articleHotMapper.selectTopByCreateTime();
        return articleHots.stream()
                .map(article -> {
                    // 计算综合得分
                    double score = calculateScore(article);

                    // 打印日志（可选）
                    log.info("热帖: id={},title={}, score={}",article.getId(), article.getTitle(), score);

                    // 转换为DTO
                    return new ArticleScoreDTO(article.getTitle(), score, article.getId());
                })
                .sorted((a, b) -> Double.compare(b.getScore(), a.getScore())) // 降序排序
                .limit(10)
                .collect(Collectors.toList());
    }

    // 权重计算抽离为独立方法
    private double calculateScore(ArticleHot article) {
        return article.getVisitCount() * 0.1
                + article.getReplyCount() * 0.6
                + article.getLikeCount() * 0.3;
    }
}
